import {
  MenuOutlined,
  SettingOutlined,
  DeleteOutlined,
  EditOutlined,
  VerticalAlignTopOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  CloseOutlined,
} from "@ant-design/icons";
import { Button, Dropdown, Input, MenuProps, Tooltip, Image } from "antd";
import { map, findIndex, forEach, pullAt } from "lodash";
import { useState, useEffect, useRef } from "react";

import LikeNoData from "../../assets/imgs/likeNoData.svg";
import WorkSpaceHeader from "../../modules/workspace/components/workspace-header";
import { ChartItem } from "../../modules/workspace/models";
import Remove from "../Remove";
import ChartItem1 from "./chartItem1";
import ChartItem2 from "./chartItem2";
import ChartParamsList from "./chartParamsList";
import ChartPropertySettings from "./chartPropertySettings";
import ParamsDataList from "./paramsDataList";

import { useWorkSpace } from "~/modules/workspace/store/use-workspace";
import "./index.scss";
import { getColumns, getParamsData } from "~/utils/chartParamsListPageination";
import eventBus from "~/utils/event";
import { Scheduler } from "~/modules/worker/schedule";

const ChartList = (props: { Open: Function }) => {
  // 图表合并/拆分标识
  const [isMerge, setIsMerge] = useState(false);
  // 获取工作区配置
  const { workSpace, update } = useWorkSpace();
  // 获取图标属性配置dom
  const chartPropertySettingsRef = useRef();
  const paramsDataListRef = useRef();
  // 工作区展示图表的配置
  const [chartCongfig, setChartConfig] = useState<ChartItem[]>([]);

  // 图表/数据表切换项
  const [items, setItems] = useState<any[]>([]);
  // 已选择的图表
  const [selectChart, setSelectChart] = useState<{
    name: string;
    index: number;
  }>({
    name: "",
    index: 0,
  });
  // 获取删除弹框的dom
  const removeRef = useRef();
  // 删除chart
  const [delText, setDelText] = useState<string>("");
  const [delChart, setDelChart] = useState<{ name: string; index: number }>({
    name: "",
    index: 0,
  });

  eventBus.on(`switchEcharts`, (value: { chart: ChartItem; index: number }) => {
    setSelectChart({ name: value.chart.name, index: value.index });
    setIsData(false);
  });

  useEffect(() => {
    setChartConfig(workSpace.splitCharts);
    getMenuItems(selectChart);
  }, [workSpace.splitCharts.length]);

  // 参数表格下拉配置
  const getMenuItems = (chart?: any) => {
    const chartsName = map(workSpace.splitCharts, (item) => {
      return item.name;
    });
    const itemsMenu = map(["数据表", ...chartsName], (item, index) => {
      return {
        label: item,
        key: index,
      };
    });
    if (chart) {
      setSelectChart(chart);
    } else {
      setSelectChart({ name: chartsName[0], index: 0 });
    }
    setItems(itemsMenu);
  };

  // 图表的合并拆分
  const onMergeSplit = (state: boolean) => {
    state ? setChartConfig([]) : setChartConfig(workSpace.splitCharts);
    setIsMerge(state);
  };

  const chartItemName = chartCongfig.map((chart: ChartItem, index: number) => {
    return (
      <div
        key={index}
        className={`w-65px z-1 flex  text-center  chart-list-chart-name-list-item ${
          chart.IsTop && "chart-list-chart-name-list-item-IsTop"
        }`}
        style={{
          top: `${
            110 + index * (Number(workSpace.setting.chartsHeight) + 60)
          }px`,
        }}
        onClick={() => onSelectChartName(chart, index)}
      >
        <div
          style={
            chart.name === selectChart.name && index === selectChart.index
              ? selectCHartStyle
              : notSelectCHartStyle
          }
        />
        <Button
          className="w-15px! h-15px! ml-2px chart-list-chart-name-list-item-delBtn"
          type="text"
          icon={<CloseOutlined />}
          onClick={() => {
            setDelText(`是否删除图表 ${chart.name} ？`);
            removeRef.current && (removeRef.current as any).onDelete();
            setDelChart({ name: chart.name, index });
          }}
        />
        <Tooltip title={chart.name}>
          <p
            className=" text-10px truncate pt-5px chart-list-chart-name-list-item-p"
            style={{
              height: `${Number(workSpace.setting.chartsHeight) + 10}px`,
            }}
          >
            {chart.name}
          </p>
        </Tooltip>
      </div>
    );
  });

  const onSelectChartName = (chart: ChartItem, index: number) => {
    setSelectChart({ name: chart.name, index });
    setIsData(false);
  };

  // 选择数据表切换
  const [isData, setIsData] = useState<boolean>(false);
  const onClick: MenuProps["onClick"] = ({ key }: any) => {
    eventBus.emit("selectChart", {
      key,
      name: items[Number(key)].label,
      index: Number(key) - 1,
    });
    key === "0" ? setIsData(true) : setIsData(false);
    setSelectChart({ name: items[Number(key)].label, index: Number(key) - 1 });
  };
  // 修改图表名称
  const onChartNameChange = (value: string) => {
    selectChart.name = value;
    setSelectChart(selectChart);
    const editChartNum: number = findIndex(
      workSpace.splitCharts,
      (item, index) => {
        return index === selectChart.index;
      }
    );
    workSpace.splitCharts[editChartNum].name = value;
    update(workSpace);
    getMenuItems(selectChart);
  };
  // 置顶
  const onTop = () => {
    forEach(workSpace.splitCharts, (item) => {
      if (item.IsTop) {
        item.IsTop = false;
      }
    });
    workSpace.splitCharts[selectChart.index].IsTop = true;
    const chart = pullAt(workSpace.splitCharts, selectChart.index);
    workSpace.splitCharts.unshift(chart[0]);
    setSelectChart({ name: selectChart.name, index: 0 });
    getMenuItems({ name: selectChart.name, index: 0 });
    update(workSpace);
  };
  // chart上移
  const onMoveUp = () => {
    const chart = pullAt(workSpace.splitCharts, selectChart.index);
    workSpace.splitCharts.splice(selectChart.index - 1, 0, chart[0]);
    selectChart.index = selectChart.index - 1;
    setSelectChart(selectChart);
    update(workSpace);
    getMenuItems(selectChart);
  };
  // chart下移
  const onMoveDown = () => {
    const chart = pullAt(workSpace.splitCharts, selectChart.index);
    workSpace.splitCharts.splice(selectChart.index + 1, 0, chart[0]);
    selectChart.index = selectChart.index + 1;
    setSelectChart(selectChart);
    update(workSpace);
    getMenuItems(selectChart);
  };
  // 图表的删除
  const onDelChartItem = () => {
    const delChartNum: number = findIndex(
      workSpace.splitCharts,
      (item, index) => {
        return item.name === delChart.name && index === delChart.index;
      }
    );
    workSpace.splitCharts.splice(delChartNum, 1);
    if (
      (600 - 32 - 60 * (workSpace.splitCharts.length + 1)) /
        workSpace.splitCharts.length <=
      100
    ) {
      workSpace.setting.chartsHeight = "100";
    } else {
      workSpace.setting.chartsHeight = String(
        (600 - 32 - 60 * (workSpace.splitCharts.length + 1)) /
          workSpace.splitCharts.length
      );
    }
    update(workSpace);
    getMenuItems();
  };

  // @ts-ignore
  return (
    <div>
      <WorkSpaceHeader
        splitType={workSpace?.splitType ?? ""}
        MergeSplit={onMergeSplit}
        Open={(value: boolean) => {
          props.Open(value);
        }}
      />
      <div className="h-600px overflow-hidden">
        <div>
          {workSpace.splitCharts.length === 0 ? (
            <div>
              <Image
                width="100%"
                height="600px"
                preview={false}
                src={LikeNoData}
              />
            </div>
          ) : isMerge ? (
            <ChartItem2 />
          ) : (
            <ChartItem1
              onDelTask={onDelChartItem}
              onSetSetDelChart={(delChartItem: {
                name: string;
                index: number;
              }) => {
                setDelChart(delChartItem);
              }}
            />
          )}
        </div>
      </div>
      <div className=" flex justify-between h-40px bg-#EBECEE border-b-2 border-#FFF pl-16px pr-16px ">
        <div className="flex">
          <Dropdown menu={{ items, onClick }} trigger={["click"]}>
            <Button
              className="w-40px! h-40px!"
              type="text"
              icon={<MenuOutlined />}
            />
          </Dropdown>
          {isData ? (
            <p style={{ lineHeight: "40px", margin: "0" }}>
              {selectChart.name}
            </p>
          ) : (
            <Input
              className="w-300px!"
              value={selectChart.name}
              prefix={<EditOutlined />}
              bordered={false}
              onChange={(e) => onChartNameChange(e.target.value)}
            />
          )}
        </div>
        <div>
          <Tooltip title="置顶">
            <Button
              className="w-40px! h-40px!"
              type="text"
              icon={<VerticalAlignTopOutlined />}
              disabled={
                workSpace.splitCharts[selectChart.index]?.IsTop || isData
              }
              onClick={() => onTop()}
            />
          </Tooltip>
          <Tooltip title="上移">
            <Button
              className="w-40px! h-40px!"
              type="text"
              icon={<ArrowUpOutlined />}
              disabled={
                selectChart.index === 0 ||
                (workSpace.splitCharts[0]?.IsTop && selectChart.index === 1) ||
                isData
              }
              onClick={() => onMoveUp()}
            />
          </Tooltip>
          <Tooltip title="下移">
            <Button
              className="w-40px! h-40px!"
              type="text"
              icon={<ArrowDownOutlined />}
              disabled={
                selectChart.index === workSpace.splitCharts.length - 1 ||
                (workSpace.splitCharts[0]?.IsTop && selectChart.index === 0) ||
                isData
              }
              onClick={() => onMoveDown()}
            />
          </Tooltip>
          <Tooltip title="属性配置">
            <Button
              className="w-40px! h-40px!"
              type="text"
              icon={<SettingOutlined />}
              disabled={isData}
              onClick={() => {
                chartPropertySettingsRef.current &&
                  (chartPropertySettingsRef.current as any).onOpen();
              }}
            />
          </Tooltip>
          <Tooltip title="图表删除">
            <Button
              className="w-40px! h-40px!"
              type="text"
              icon={<DeleteOutlined />}
              disabled={isMerge || isData}
              onClick={() => {
                setDelText(`是否删除图表 ${selectChart.name} ？`);
                removeRef.current && (removeRef.current as any).onDelete();
                setDelChart({
                  name: selectChart.name,
                  index: selectChart.index,
                });
              }}
            />
          </Tooltip>
        </div>
      </div>
      <div className="pl-16px pr-16px">
        {isData ? (
          <ParamsDataList ref={paramsDataListRef} />
        ) : (
          <ChartParamsList
            isMerge={isMerge}
            chartName={selectChart.name}
            chartIndex={selectChart.index}
          />
        )}
      </div>
      <ChartPropertySettings
        ref={chartPropertySettingsRef}
        isMerge={isMerge}
        name={selectChart.name}
        chartNum={selectChart.index}
        chartChange={() => {
          getMenuItems(selectChart);
        }}
      />
      <Remove ref={removeRef} delText={delText} onDelTask={onDelChartItem} />
    </div>
  );
};

export default ChartList;

const selectCHartStyle = {
  width: "3px",
  backgroundColor: "#1890ff",
};
const notSelectCHartStyle = {
  width: "3px",
};
